package com.example.week10_spring_security.service;

import com.example.week10_spring_security.entity.Goods;
import com.example.week10_spring_security.repo.GoodsRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Component
public class GoodsService {

    @Autowired
    private GoodsRepo goodsRepo;

    public GoodsService() {
        // TODO document why this constructor is empty
    }

    public Goods addGoods(Goods goods) {
        return goodsRepo.saveAndFlush(goods);
    }

    public List<Goods> getGoodsBySupplierId(Long id) {
        return goodsRepo.findBySupplierId(id);
    }

    public Goods getGoodsById(Long id) {
        return goodsRepo.findById(id).orElse(null);
    }

    public Goods updateGoods(Goods goods) {
        return goodsRepo.save(goods);
    }

    public void deleteGoodsById(Long id) {
        goodsRepo.deleteById(id);
    }

    public List<Goods> getAllGoods() {
        return goodsRepo.findAll();
    }

    public List<Goods> getGoodsByNameAndPriceBetween(String name, Double minPrice, Double maxPrice) {
        return goodsRepo.findByNameContainingAndPriceBetween(name, minPrice, maxPrice);
    }

    public List<Goods> getGoodsByNamesLike(List<String> names) {
        Specification specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            for (String name : names) {
                list.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            Predicate[] predicates = list.toArray(new Predicate[list.size()]);
            return criteriaBuilder.or(predicates);
        };

        return goodsRepo.findAll(specification);
    }


}
